package rocket.client;

import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * @author justin
 * @version
 *the true end-user experience
 */
public class Client {
	
	static private final String host = "localhost";
	
	private Socket socket;
	
	private PrintWriter out;
	
	private BufferedReader in;
	
	private JTextField textField;
	
	private InetAddress address;

	/**
	 * lift-off!
	 */
	public void launch() {
		JFrame login = new Login();
		textField = new JTextField();
		login.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		login.setMinimumSize(Login.minSize);
		login.setVisible(true);
	}
	
	/**
	 * Be very very quiet, I'm hunting rabbits!
	 */
	public void listenSocket() {
		try {
			address = InetAddress.getByName(host);
			socket = new Socket(address, 1337);
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @param event
	 */
	public void actionPerformed(ActionEvent event) {
		final Object source = event.getSource();
		
		if (source instanceof JButton) {
			final String text = textField.getText();
			out.println(text);
			textField.setText("");
		}
		
		try {
			String line = in.readLine();
			System.out.println("Received: " + line);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	  /* (non-Javadoc)
	 * @see java.lang.Object#finalize()
	 */
	protected void finalize(){
		//Objects created in run method are finalized when 
		//program terminates and thread exits
		 try{
		    socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		    System.out.println("Could not close socket");
		    System.exit(-1);
		}
	}
	
	public String toString(){
		return "Client";
	}
}
